﻿using System;
using fastCSharp;
using fastCSharp.code.cSharp;

namespace diantou.web.exam
{
    /// <summary>
    /// 
    /// </summary>
    partial class webSocket<socketType> : webSocket.socket<socketType>
        where socketType : webSocket<socketType>
    {
        /// <summary>
        /// 服务器端异常消息返回
        /// </summary>
        protected static readonly byte[] exceptionData = new byte[] { 0 };
        /// <summary>
        /// 成功消息返回
        /// </summary>
        protected static readonly byte[] successData = new byte[] { 1 };
        /// <summary>
        /// 数据错误消息返回
        /// </summary>
        protected static readonly byte[] errorData = new byte[] { 2 };
        /// <summary>
        /// 跨域验证错误消息返回
        /// </summary>
        protected static readonly byte[] verifyErrorData = new byte[] { 3 };
        /// <summary>
        /// 跨域验证过期消息返回
        /// </summary>
        protected static readonly byte[] verifyExpiredData = new byte[] { 4 };
        /// <summary>
        /// 考试用户标识
        /// </summary>
        protected int userId;
        /// <summary>
        /// 考试用户会话标识
        /// </summary>
        protected int sessionId;
        /// <summary>
        /// 跨域登录处理
        /// </summary>
        /// <param name="dataStart"></param>
        /// <param name="size"></param>
        /// <param name="returnData"></param>
        protected unsafe void login(byte* dataStart, int size, ref byte[] returnData)
        {
            if (size == 1 + 4 + 4 + 4)
            {
                int userId = *(int*)(dataStart + 1), sessionId = *(int*)(dataStart + 5);
                uint verifyCode = *(uint*)(dataStart + 9);
                if (userId > 0 && sessionId > 0 && verifyCode != 0)
                {
                    if (((userId ^ this.userId) | (sessionId ^ this.sessionId)) == 0)
                    {
                        returnData = successData;
                        return;
                    }
                    switch (problem.AnswerCacheClient.checkVerifyCode(userId, sessionId, verifyCode).Value)
                    {
                        case 1:
                            returnData = successData;
                            this.userId = userId;
                            this.sessionId = sessionId;
                            return;
                        case 2: returnData = verifyExpiredData; return;
                        default: returnData = verifyErrorData; return;
                    }
                }
            }
            returnData = errorData;
        }

    }
}
